package com.dayuanit.dy15.atm.util;

import com.dayuanit.dy15.atm.session.MySession;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtils {

//    private static final Map<String, HttpSession> sessionMap = new HashMap<>();

    //Hashtable是线程安全的，通过对每个方法加上同步代码块，但是锁的力度太粗，性能就低。
//    private static final Map<String, HttpSession> sessionMap = new Hashtable<>();

    //******** 换成JUC包下面的ConcurrentHashMap，既能保证线程安全，性能也不错。*******
    private static final Map<String, HttpSession> sessionMap = new ConcurrentHashMap<>();

    public static HttpSession getSession(HttpServletRequest request, HttpServletResponse response) {

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("mySessionId")) {
                    String mySessionId = cookie.getValue();
                    HttpSession httpSession = sessionMap.get(mySessionId);
                    if (httpSession != null) {
                      return httpSession;
                    }
                }
            }
        }

        //如果请求的cookie中木有根据sessionId找到对应的session对象，则新建session对象
        MySession mySession = new MySession();
        sessionMap.put(mySession.getId(), mySession);

        Cookie cookie = new Cookie("mySessionId", mySession.getId());
        response.addCookie(cookie);
        return mySession;
    }
}
